import { apiRequest } from '@/utils/apiRequest'
import { ElMessage } from 'element-plus'

/**
 * 获取仓库列表（带分页和搜索）
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页条数
 * @param {string} [params.warehouseCode] - 仓库编码
 * @param {string} [params.warehouseName] - 仓库名称
 * @param {string} [params.status] - 状态
 * @returns {Promise<{data: {items: Array, total: number}}>}
 */
export const getWarehouseList = async (params) => {
  try {
    const response = await apiRequest.get('/api/Warehouses/paged', {
      params: {
        page: params.page,
        pageSize: params.pageSize,
        warehouseCode: params.warehouseCode,
        warehouseName: params.warehouseName,
        status: params.status
      }
    })
    return response.data
  } catch (error) {
    console.error('Failed to load warehouse list:', error)
    ElMessage.error('获取仓库列表失败: ' + error.message)
    throw error
  }
}

/**
 * 获取单个仓库
 * @param {string|number} id - 仓库ID
 * @returns {Promise<any>}
 */
export const getWarehouseById = async (id) => {
  try {
    const response = await apiRequest.get(`/api/Warehouses/${id}`)
    return response.data
  } catch (error) {
    console.error(`Failed to get warehouse by id ${id}:`, error)
    ElMessage.error('获取仓库详情失败: ' + error.message)
    throw error
  }
}

/**
 * 创建仓库
 * @param {Object} data - 仓库数据
 * @returns {Promise<any>}
 */
export const createWarehouse = async (data) => {
  try {
    const response = await apiRequest.post('/api/Warehouses', data)
    ElMessage.success('创建仓库成功')
    return response.data
  } catch (error) {
    console.error('Failed to create warehouse:', error)
    ElMessage.error('创建仓库失败: ' + error.message)
    throw error
  }
}

/**
 * 更新仓库
 * @param {string|number} id - 仓库ID
 * @param {Object} data - 仓库数据
 * @returns {Promise<any>}
 */
export const updateWarehouse = async (id, data) => {
  try {
    const response = await apiRequest.put(`/api/Warehouses/${id}`, data)
    ElMessage.success('更新仓库成功')
    return response.data
  } catch (error) {
    console.error(`Failed to update warehouse ${id}:`, error)
    ElMessage.error('更新仓库失败: ' + error.message)
    throw error
  }
}

/**
 * 删除仓库
 * @param {string|number} id - 仓库ID
 * @returns {Promise<void>}
 */
export const deleteWarehouse = async (id) => {
  try {
    await apiRequest.delete(`/api/Warehouses/${id}`)
    ElMessage.success('删除仓库成功')
  } catch (error) {
    console.error(`Failed to delete warehouse ${id}:`, error)
    ElMessage.error('删除仓库失败: ' + error.message)
    throw error
  }
}